﻿using FrameworkCore.Constants;
using Microsoft.Data.SqlClient;
using Microsoft.Extensions.Configuration;
using System.Text.RegularExpressions;

namespace FrameworkCore.Migrations;

public abstract partial class BaseDataProvider
{
    #region 构造函数
    protected BaseDataProvider()
    {
    }
    #endregion

    #region 创建数据库
    private string databaseNamePattern = @"\s*;\s*Database\s*=\s*([^;]+)\s*;\s*";
    private string connectionStringPattern = @"(?i)Database=";
    public virtual string DatabaseName => CommonHelper.MatchString(ConnectionString, databaseNamePattern).Trim();

    public virtual string ConnectionString => ConfigurationsExtensions.GetGlobalSection<string>(GlobalConstants.DefaultConnectionKey);

    public virtual bool CreateDatabaseIfNotExists(string? connectionString = default)
    {
        var databaseName = connectionString == default ? DatabaseName : CommonHelper.MatchString(connectionString, databaseNamePattern);
        connectionString = connectionString ?? ConnectionString;
        connectionString = Regex.Replace(connectionString, connectionStringPattern, "").Replace(databaseName, "");

        // 检查数据库是否已经存在
        if (DatabaseExists(databaseName, connectionString))
        {
            Console.WriteLine($"Database '{databaseName}' already exists.");
            return false;
        }

        // 创建数据库的 SQL 查询字符串
        string createDatabaseQuery = $"CREATE DATABASE [{databaseName}]";

        using (SqlConnection connection = new SqlConnection(connectionString))
        {
            try
            {
                connection.Open();
                using (SqlCommand command = new SqlCommand(createDatabaseQuery, connection))
                {
                    command.ExecuteNonQuery();
                    Console.WriteLine($"Database '{databaseName}' created successfully.");
                    return true;
                }
            }
            catch (SqlException ex)
            {
                Console.WriteLine($"Error creating database '{databaseName}': {ex.Message}");
                return false;
            }
            catch (Exception ex)
            {
                Console.WriteLine($"Error creating database '{databaseName}': {ex.Message}");
                return false;
            }
        }
    }

    public virtual bool DatabaseExists(string? databaseName = default, string? connectionString = default)
    {
        connectionString = connectionString ?? ConnectionString;
        databaseName = databaseName ?? DatabaseName;
        string query = "SELECT COUNT(*) FROM sys.databases WHERE name = @databaseName";
        using (SqlConnection connection = new SqlConnection(connectionString))
        {
            using (SqlCommand command = new SqlCommand(query, connection))
            {
                command.Parameters.AddWithValue("@databaseName", databaseName);
                connection.Open();
                int result = (int)command.ExecuteScalar();
                return result > 0;
            }
        }
    }
    #endregion
}
